import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES } from '../../utils/errorCodes';

export class ClientBadgeController extends BaseController {
  // 获取用户徽章
  async getUserBadges(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const userId = req.user?.id;
      if (!userId) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.USER_NOT_FOUND, '用户不存在');
        return;
      }

      const userBadges = await prisma.userBadge.findMany({
        where: {
          userId: userId
        },
        include: {
          badge: {
            select: {
              id: true,
              name: true,
              description: true,
              icon: true,
              type: true,
              conditionType: true,
              conditionValue: true
            }
          }
        },
        orderBy: {
          earnedAt: 'desc'
        }
      });

      // 格式化结果
      const formattedBadges = userBadges.map(item => ({
        id: item.badge.id,
        name: item.badge.name,
        description: item.badge.description,
        icon: item.badge.icon,
        type: item.badge.type,
        conditionType: item.badge.conditionType,
        conditionValue: item.badge.conditionValue,
        obtainedAt: item.earnedAt
      }));

      ResponseUtils.success(res, formattedBadges, '获取用户徽章成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取所有徽章
  async getAllBadges(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, pageSize = 20 } = req.query;
      const skip = (Number(page) - 1) * Number(pageSize);

      const badges = await prisma.badge.findMany({
        skip: skip,
        take: Number(pageSize),
        select: {
          id: true,
          name: true,
          description: true,
          icon: true,
          type: true,
          conditionType: true,
          conditionValue: true
        },
        orderBy: {
          name: 'asc'
        }
      });

      // 获取总数
      const total = await prisma.badge.count();

      ResponseUtils.success(res, {
        items: badges,
        pagination: {
          total,
          page: Number(page),
          pageSize: Number(pageSize),
          totalPages: Math.ceil(total / Number(pageSize))
        }
      }, '获取所有徽章成功');
    } catch (error) {
      next(error);
    }
  }
}